package com.starryx.blog.web;

import com.starryx.blog.po.Type;
import com.starryx.blog.service.BlogService;
import com.starryx.blog.service.TypeService;
import com.starryx.blog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class TypeShowController {       // 控制器类最好不要重名

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    @GetMapping("/types/{id}")
    public  String types(@PageableDefault(size = 10, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @PathVariable Long id,
                         Model model){
        List<Type> types = typeService.listTypeTop(10000);      // 这里只要数目足够大，就不会超出分类的数量，实际上是偷懒，其实可以多写一个方法
        if(id == -1){
            id = types.get(0).getId();      // 若无指定id(id == -1)，即第一次跳转到分类展示页面，就默认第一个
        }
        BlogQuery blogQuery = new BlogQuery();
        blogQuery.setTypeId(id);        // 将 分类id 作为查询条件
        model.addAttribute("types", types);
        model.addAttribute("page", blogService.listBlog(pageable, blogQuery));
        model.addAttribute("activeTypeId", id);     // 将传来的 id 再传回去，用于指定那个分类是高亮
        return "types";
    }
}
